package com.mings.ai.service;

import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RagService {

    private final VectorStore vectorStore;
    private final DeepSeekChatModel deepSeekChatModel;

    public RagService(VectorStore vectorStore, DeepSeekChatModel deepSeekChatModel) {
        this.vectorStore = vectorStore;
        this.deepSeekChatModel = deepSeekChatModel;
    }

    public String query(String question, int topK) {
        SearchRequest searchRequest = SearchRequest.builder()
                .query(question)
                .topK(topK)
                .build();
        // 1. 从向量库检索相关文档
        List<Document> relevantDocs = vectorStore.similaritySearch(searchRequest);

        // 2. 构建提示词
        String context = relevantDocs.stream()
                .map(Document::getText)
                .collect(Collectors.joining("\n\n"));

        String prompt = String.format("""
            基于以下上下文信息回答问题。如果无法从上下文中得到答案，请回答"我不知道"。
            
            上下文：
            %s
            
            问题：%s
            """, context, question);

        // 3. 调用大模型生成回答
        return deepSeekChatModel.call(prompt);
    }
}
